package com.young.core.dao.impl;


import com.young.common.query.Pagination;
import com.young.common.query.PaginationBuilder;
import com.young.common.query.Query;
import com.young.core.dao.BaseDao;
import com.young.core.dao.JobDao;
import com.young.core.domain.JobDO;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class JobDaoImpl extends BaseDao implements JobDao {

    @Override
    public void insert(JobDO jobInfo) {
        this.sqlSession.insert("JobMapper.insert", jobInfo);
    }

    @Override
    public int update(JobDO jobInfo) {
        return this.sqlSession.update("JobMapper.update", jobInfo);
    }

    @Override
    public int updateStatus(int id, int status,String operator) {
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("id", id);
        parameters.put("status", status);
        parameters.put("operator", operator);
        return this.sqlSession.update("JobMapper.updateStatus", parameters);
    }

    @Override
    public int batchUpdate(String project, Collection<Integer> ids, Map<String,Object> fields) {
        Map<String, Object> parameters = new HashMap<>();
        parameters.putAll(fields);
        parameters.put("project", project);
        parameters.put("ids", ids);
        return this.sqlSession.update("JobMapper.batchUpdate", parameters);
    }

    @Override
    public void delete(int id) {
        this.sqlSession.delete("JobMapper.delete", id);
    }

    @Override
    public JobDO get(int id) {
        return this.sqlSession.selectOne("JobMapper.getById", id);
    }

    @Override
    public JobDO get(String uniqueCode) {
        return this.sqlSession.selectOne("JobMapper.getByUniqueCode", uniqueCode);
    }

    @Override
    public Pagination<JobDO> query(Query query) {
        Map<String, Object> parameters = query.buildParameters();
        int amount = amount(parameters);
        PaginationBuilder<JobDO> builder = PaginationBuilder.query(query);
        builder.amount(amount);
        if (amount > 0) {
            List<JobDO> list = this.sqlSession.selectList("JobMapper.query", parameters);
            builder.result(list);
        } else {
            builder.result(new ArrayList<>());
        }
        return builder.build();
    }

    @Override
    public int count(String project) {
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("project", project);
        return amount(parameters);
    }

    @Override
    public List<JobDO> getAll(String project) {
        return this.sqlSession.selectList("JobMapper.getByProject",project);
    }

    private int amount(Map<String, Object> parameters) {
        return this.sqlSession.selectOne("JobMapper.getAmount", parameters);
    }

}
